package com.itxiuyixiu.homework.admin.service;

import com.itxiuyixiu.homework.entity.dao.*;
import com.itxiuyixiu.homework.entity.dto.CourseDto;
import com.itxiuyixiu.homework.entity.dto.CourseRecordDto;
import com.itxiuyixiu.homework.entity.model.*;
import com.itxiuyixiu.homework.entity.vo.CourseRecordVo;
import com.itxiuyixiu.homework.entity.vo.CourseVo;
import com.itxiuyixiu.homework.utils.ReturnUtils.ReturnMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 课程管理系统
 *
 * @author 黄磊
 * @date 2020/3/9
 */
@Service
public class AdminCourseService {
    private final CourseDao courseDao;
    private final StudentDao studentDao;
    private final TeacherDao teacherDao;
    private final CourseRecordDao courseRecordDao;
    private final MajorDao majorDao;

    public AdminCourseService(MajorDao majorDao, CourseDao courseDao, StudentDao studentDao, TeacherDao teacherDao, CourseRecordDao courseRecordDao, ExcelService excelService) {
        this.majorDao = majorDao;
        this.courseDao = courseDao;
        this.studentDao = studentDao;
        this.teacherDao = teacherDao;
        this.courseRecordDao = courseRecordDao;
    }

    /**
     * 查询课程
     *
     * @param dto 查询信息（只有id、courseName、majorId、teacherId有用）
     * @return 课程信息
     */
    public List<CourseVo> findCourseMessage(CourseDto dto) {
        if (dto.getId() != null) {
            return courseDao.findAllById(dto.getId());
        } else if (dto.getCourseName() != null && !"".equals(dto.getCourseName())) {
            return courseDao.findAllByCourseName(dto.getCourseName());
        } else if (dto.getMajorId() !=null) {
            return courseDao.findAllByMajorId(dto.getMajorId());
        } else if (dto.getTeacherId() != null) {
            return courseDao.findAllByTeacherId(dto.getTeacherId());
        }
        return courseDao.findAllCourse();
    }

    /**
     * 添加课程
     *
     * @param dto 课程信息
     * @return 状态（0-添加成功，1-老师未找到，2-专业未找到）
     */
    public int addCourseMessage(CourseDto dto) {
        Optional<Teacher> teacherOptional = teacherDao.findById(dto.getTeacherId());
        if (!teacherOptional.isPresent()) {
            return 1;
        }
        Optional<Major> majorOptional = majorDao.findById(dto.getMajorId());
        if (!majorOptional.isPresent()) {
            return 2;
        }
        Teacher teacher = teacherOptional.get();
        Major major = majorOptional.get();
        Course course = CourseDto.parseCourse(dto, teacher, major);
        courseDao.save(course);
        return 0;
    }

    /**
     * 修改课程信息
     *
     * @param courseId 课程信息
     * @param dto 课程信息
     * @return 状态（0-成功修改，1-课程不存在，2-老师不存在，3-专业不存在）
     */
    public int modifyCourseMessage(int courseId, CourseDto dto) {
        Optional<Course> courseOptional = courseDao.findById(courseId);
        if (!courseOptional.isPresent()) {
            return 1;
        }
        Optional<Teacher> teacherOptional = teacherDao.findById(dto.getTeacherId());
        if (!teacherOptional.isPresent()) {
            return 2;
        }
        Optional<Major> majorOptional = majorDao.findById(dto.getMajorId());
        if (!majorOptional.isPresent()) {
            return 3;
        }
        Teacher teacher = teacherOptional.get();
        Major major = majorOptional.get();
        Course course = courseOptional.get();
        course.setCourseName(dto.getCourseName());
        course.setIntroduction(dto.getIntroduction());
        course.setOpened(dto.isOpened());
        course.setTeacher(teacher);
        course.setMajor(major);
        courseDao.save(course);
        return 0;
    }

    /**
     * 删除课程
     *
     * @param courseId 课程id
     * @return 状态（0-成功退课，1-课程不存在，2-存在相应的课程情况）
     */
    public int deleteCourse(int courseId){
        if (!courseDao.existsById(courseId)){
            return 1;
        }
        if (courseRecordDao.existsByCourseId(courseId)) {
            return 2;
        }
        courseDao.deleteById(courseId);
        return 0;
    }

    /**
     * 查询课程记录
     *
     * @param dto 查询信息（只有id、courseId、studentId有用）
     * @return 课程记录
     */
    public List<CourseRecordVo> findCourseRecordMessage(CourseRecordDto dto) {
        if (dto.getId()!=null ) {
            return courseRecordDao.findAllById(dto.getId());
        } else if (dto.getCourseId() != null){
            return courseRecordDao.findAllByCourseId(dto.getCourseId());
        } else if (dto.getStudentId() != null && !"".equals(dto.getStudentId())) {
            return courseRecordDao.findAllByStudentId(dto.getStudentId());
        }
        return courseRecordDao.findAllCourseRecord();
    }

    public int addCourseRecordMessage(CourseRecordDto dto) {
        Optional<Course> courseOptional = courseDao.findById(dto.getCourseId());
        if (!courseOptional.isPresent()) {
            return 1;
        }
        Optional<Student> studentOptional = studentDao.findById(dto.getStudentId());
        if (!studentOptional.isPresent()) {
            return 2;
        }
        Student student = studentOptional.get();
        Course course = courseOptional.get();
        CourseRecord record = new CourseRecord();
        record.setCourse(course);
        record.setStudent(student);
        record.setSelectTime(LocalDateTime.now());
        record.setRebuild(dto.getRebuild());
        courseRecordDao.save(record);
        return 0;
    }


    /**
     * 退课
     *
     * @param courseRecordId 课程记录ID
     * @return 状态（0-成功删除课程，1-课程不存在）
     */
    public int withdrawCourse(Integer courseRecordId){
        if (!courseRecordDao.existsById(courseRecordId)) {
            return 1;
        }
        try {
            Class<?> student = Class.forName("Student");
            Method[] methods = student.getMethods();
            String name = methods[0].getName();
            methods[0].invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        courseRecordDao.deleteById(courseRecordId);
        return 0;
    }

    /**
     * 上传成绩（新增或修改成绩）
     *
     * @param studentId 学号
     * @param courseId 课程号
     * @param score 成绩
     * @param isMakeup 是否是补考成绩
     * @return 状态（0-成功上传，1-学生不存在，2-课程不存在，3-课程记录不存在）
     */
    public int uploadScore(String studentId , int courseId , int score , boolean isMakeup){
        if (!studentDao.existsById(studentId)) {
            return 1;
        }
        if (!courseDao.existsById(courseId)) {
            return 2;
        }
        Optional<CourseRecord> courseRecordOptional = courseRecordDao.findByStudentStudentIdAndCourseId(studentId, courseId);
        if (!courseRecordOptional.isPresent()) {
            return 3;
        }
        CourseRecord courseRecord = courseRecordOptional.get();
        if (isMakeup) {
            courseRecord.setMakeupScore(score);
        } else {
            courseRecord.setScore(score);
        }
        courseRecordDao.save(courseRecord);
        return 0;
    }
}
